Overview

  • Hour 1
    • Object-oriented programming
    • GUI programming
  • Hour 2
    • Git
    • Review
  • Hour 3
    • Work time

Review: OO Concepts

Objects

  • Objects are created from abstract data types that encapsulate data and functionality together.
  • Idea: Objects, or data representations, are more stable than functionality.
  • Also called encapsulation

  • Information hiding
  • Object reusability

Functions attached to an object are called methods.

Classes

  • A class is the code that specifies the data attributes and methods for a particular type of object.
  • They are like blueprints or cookie cutters

In [15]:
import random

# The Coin class simulates a coin that can be flipped

class Coin:
    # The __init__ methods is the constructor
    
    def __init__(self):
        self.sideup = 'Heads'
    
    def toss(self):
        flip = random.randint(0, 1)
        if flip == 0:
            self.sideup = "Heads"
        else:
            self.sideup = "Tails"
    
    def get_sideup(self):
        return self.sideup

In [17]:
def main():
    my_coin = Coin()
    
    print("This side is up: " + my_coin.get_sideup())
    
    print("I am tossing the coin...")
    my_coin.toss()
    
    print("This side is up: " + my_coin.get_sideup())

main()


This side is up: Heads
I am tossing the coin...
This side is up: Tails

Graphical User Interface (GUI)

A graphical user interface allows the user to interact with the operating system and other programs using graphical elements such as icons, buttons, and dialog boxes.

A great way to explain object-oriented programming, because in a GUI everything is an object.

GUI Programs are Event-Driven

They respond to the actions of the user. The user causes events to take place, such as clicking a button, and the program must respond to the events.

Tkinter Module

Tkinter is short for "Tk interface." Tk is a GUI library that works with many programming languages.

Many GUI libraries are available for Python. Tkinter is distributed with Python, so nothing else needs to be installed.


In [18]:
import Tkinter

class MainWindow:
    def __init__(self):
        # Create the main window widget
        self.main_window = Tkinter.Tk()
        
        # Enter the Tkinter main loop
        Tkinter.mainloop()

# Create an instance of the MainWindow class
mw = MainWindow()

Let's make a GUI for the Name That Shape Program

It should look like this.


In [ ]:

Adding and Packing Label Widgets


In [19]:
import Tkinter

class NameThatShapeGUI:
    def __init__(self):
        # Create the main window widget
        self.main_window = Tkinter.Tk()
        
        # Create a Label widget containing the 
        self.label = Tkinter.Label(self.main_window, text = "Enter the number of sides in the shape")
        
        # Call the Label widget's pack methods
        self.label.pack()
        
        # Enter the Tkinter main loop
        Tkinter.mainloop()

# Create an instance of the NameThatShapeGUI class
ntsg = NameThatShapeGUI()

Button Widgets and Info Dialog Boxes

The Button widget is used to create buttons in windows. When a user clicks a button, a specified function or method is called.

An info dialog box is a simple window that displays a message to the user and has an OK button that dismisses the dialog box.


In [20]:
import Tkinter
import tkMessageBox

class NameThatShapeGUI:

    def __init__(self):
        # Create the main window widget
        self.main_window = Tkinter.Tk()

        # Create a Button widget
        self.my_button = Tkinter.Button(self.main_window,
                                        text="Name",
                                        command=self.do_something)

        # Call the Button widget's pack methods
        self.my_button.pack()

        # Enter the Tkinter main loop
        Tkinter.mainloop()

    def do_something(self):
        # Display and info dialog box
        tkMessageBox.showinfo("Response", "Thanks for clicking")

# Create an instance of the NameThatShapeGUI class
ntsg = NameThatShapeGUI()

Getting Input with the Entry Widget

An Entry widget is a rectangular area that the user can type input into. You use the Entry widget's get method to retrieve the data that has been typed into the widget.


In [8]:

Using Labels as Output Fields

When a StringVar object is associated with a Label widget, the Label widget displays any data that is stored in the StringVar object.


In [14]:
import Tkinter
import tkMessageBox


class NameThatShapeGUI:
    def __init__(self):
        # Create the main window widget
        self.main_window = Tkinter.Tk()
        self.main_window.geometry('500x100')

        # Create two frames to group widgets
        self.top_frame = Tkinter.Frame(self.main_window)
        self.middle_frame = Tkinter.Frame(self.main_window)
        self.bottom_frame = Tkinter.Frame(self.main_window)

        # Create widgets for the top frame
        self.prompt_label = Tkinter.Label(self.top_frame,
                                          text="Enter the number of sides in the shape:")
        self.side_entry = Tkinter.Entry(self.top_frame, width=10)

        # Pack the top frame's widgets
        self.prompt_label.pack(side="left")
        self.side_entry.pack(side="left")

        # Create widgets for the middle frame
        self.descr_label = Tkinter.Label(self.middle_frame, text="Name of shape:")
        self.value = Tkinter.StringVar()
        self.value.set("")
        self.shape_name = Tkinter.Label(self.middle_frame, textvariable=self.value)

        # Pack the middle frame's widgets
        self.descr_label.pack(side="left")
        self.shape_name.pack(side="left")


        # Create widgets for bottom frame
        self.conv_button = Tkinter.Button(self.bottom_frame,
                                          text="Name",
                                          command=self.convert)

        self.quit_button = Tkinter.Button(self.bottom_frame,
                                          text="Quit",
                                          command=self.main_window.destroy)

        # Pack the bottom buttons
        self.conv_button.pack(side="left")
        self.quit_button.pack(side="left")

        # Pack the frames
        self.top_frame.pack()
        self.middle_frame.pack()
        self.bottom_frame.pack()


        # Enter the Tkinter main loop
        Tkinter.mainloop()

    def convert(self):
        # Display and info dialog box
        self.value.set(self.side_entry.get())
        tkMessageBox.showinfo("Response", self.side_entry.get())

# Create an instance of the MainWindow class
ntsg = NameThatShapeGUI()

Git

  • See slides from Week 2

Rules of Programming

Rule 0. Don't panic.

Rule 1. Think before you program.

Rule 2. A program is a human-readable essay on problem solving tht also happens to execute on a computer.

Rule 3. The best way to improve your programming and problem skills is to practice.

Rule 4. A foolish consistency is the hobgoblin of little minds.

Rule 5. Test your code, often and thoroughly.

Rule 6. If it was hard to write, it is probably hard to read. Add a comment.

Rule 7. All input is evil, until proven otherwise.

Rule 8. A function should do one thing.

Topics for Test

  • Interpreters
  • Rules of Programming
  • Variables
  • Data Types
    • Mutability
  • Input, processing, and output
    • Keyboard input
    • Screen output
  • Decision structures (if/elif/else)
  • Boolean expressions and operators
  • Reptition structures
    • Condition controlled (while)
    • Count controlled (for)
      • range function
  • Strings
    • Indexing
    • Slicing
  • Exceptions
    • try/except
    • raise
  • Composite Data Structures
    • Lists
    • Tuple
    • Dictionary
    • Set
  • Programming Style
  • Testing
  • Decomposition
    • Modules
    • Functions and methods
    • Classes
  • Files I/O
  • JSON
  • Regular Expressions
  • Git

In [ ]: